// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <cantor/transform/transform.h>
#include <cantor/transform/stmt.h>
#include <cantor/transform/utility.h>
#include <cantor/version.h>
#include <turbo/times/time.h>

namespace cantor::transform {

    const turbo::Status &Transform::resolve_ast(const cantor::parser::SqlParser * parser) {
        KCHECK(parser)<<"parser is nullptr";
        turbo::TimeCost time_cost;
        stmts.Clear();
        if (parser->error != cantor::parser::ParseError::SUCCESS) {
            status = turbo::internal_error(parser->syntax_err_str);
            set_proto_status(status, stmts.mutable_status());
            return status;
        }

        if (parser->result.empty()) {
            status = turbo::internal_error("empty result");
            set_proto_status(status, stmts.mutable_status());
            return status;
        }

        auto sts = stmts.mutable_statements();
        sts->Reserve(parser->result.size());
        for (size_t i = 0; i < parser->result.size(); i++) {
            auto stmt = sts->Add();
            status = TransStmt::resolve_to(parser->result[i], stmt);
            if (!status.ok()) {
                set_proto_status(status, stmts.mutable_status());
                return status;
            }
        }
        stmts.set_parse_cost_nano(parser->parse_cost_nano);
        auto mv = stmts.mutable_version();
        mv->set_major(CANTOR_VERSION_MAJOR);
        mv->set_minor(CANTOR_VERSION_MINOR);
        mv->set_patch(CANTOR_VERSION_PATCH);
        stmts.set_transform_cost_nano(time_cost.n_elapsed());
        set_proto_status(status, stmts.mutable_status());
        return status;
    }

    const turbo::Status &Transform::resolve_ast(const std::string &sql) {
        cantor::parser::SqlParser parser;
        parser.parse(sql);
        return resolve_ast(&parser);
    }

}  // namespace cantor::transform
